#include "server_user.h"

void write_log(const char *format, ...);

int _row_to_userInfo(MYSQL_ROW row, userInfo_t *user)
{
    if (row == NULL || user == NULL)
    {
        return -1;
    }

    // name
    if (row[1] != NULL)
    {
        strncpy(user->_name, row[1], sizeof(user->_name) - 1);
        user->_name[sizeof(user->_name) - 1] = '\0';
    }
    else
    {
        user->_name[0] = '\0';
    }

    // salt
    if (row[2] != NULL)
    {
        strncpy(user->_salt, row[2], sizeof(user->_salt) - 1);
        user->_salt[sizeof(user->_salt) - 1] = '\0';
    }
    else
    {
        user->_salt[0] = '\0';
    }

    // encrypted
    if (row[3] != NULL)
    {
        strncpy(user->_encrypted, row[3], sizeof(user->_encrypted) - 1);
        user->_encrypted[sizeof(user->_encrypted) - 1] = '\0';
    }
    else
    {
        user->_encrypted[0] = '\0';
    }

    // pwd
    if (row[5] != NULL)
    {
        strncpy(user->_pwd, row[5], sizeof(user->_pwd) - 1);
        user->_pwd[sizeof(user->_pwd) - 1] = '\0';
    }
    else
    {
        user->_pwd[0] = '\0';
    }

    return 0;
}

int _find_user(MYSQL *mysql, const char *clientUsername, userInfo_t *user)
{
    if (mysql == NULL || clientUsername == NULL || user == NULL)
    {
        write_log("Invalid input parameters.");
        return -1;
    }

    char sql[512] = {0};
    snprintf(sql, sizeof(sql),
             "SELECT Users.*, FakeFiles.path FROM Users "
             "LEFT JOIN FakeFiles ON Users.path_id = FakeFiles.id "
             "WHERE Users.username = '%s'",
             clientUsername);

    if (mysql_query(mysql, sql) != 0)
    {
        write_log("mysql_query failed: %s", mysql_error(mysql));
        return -1;
    }

    MYSQL_RES *table = mysql_store_result(mysql);
    if (table == NULL)
    {
        write_log("mysql_store_result failed: %s", mysql_error(mysql));
        return -1;
    }

    MYSQL_ROW row = mysql_fetch_row(table);
    if (row == NULL)
    {
        write_log("User not found: %s", clientUsername);
        mysql_free_result(table);
        return -1;
    }

    int ret = _row_to_userInfo(row, user);
    mysql_free_result(table);
    return ret;
}

int _print_user(userInfo_t* user) {
    if (user == NULL) {
        fprintf(stderr, "Error: NULL user pointer\n");
        return -1;
    }

    printf("=== User Info Debug ===\n");
    printf("Socket FD:    %d\n", user->_sockfd);
    printf("Login Status: %s\n", user->_status == STATUS_LOGOFF ? "LOGOFF" : "LOGIN");
    printf("Username:     %.*s\n", (int)sizeof(user->_name), user->_name);
    printf("Salt:         %.*s\n", (int)sizeof(user->_salt), user->_salt);
    printf("Encrypted:    %.*s\n", (int)sizeof(user->_encrypted), user->_encrypted);
    printf("Path:         %.*s\n", (int)sizeof(user->_pwd), user->_pwd);
    printf("=======================\n");
    return 0;
}